﻿namespace MicroCloud.AspNetCore.Routing
{
    /// <summary>
    /// 终结点模块(Endpoints)基类
    /// <para>处理MVC和SignalR的路由结点配置</para>
    /// </summary>
    [Description("终结点模块(Endpoints)")]
    [DependsOnPacks(typeof(AspNetCorePack), typeof(MvcPack))]
    public abstract class EndpointsPackBase : AspPackBase
    {
        #region "属性"
        #region "获取 模块级别"
        /// <summary>
        /// 获取 模块级别
        /// <para>级别越小越先启动</para>
        /// </summary>
        public override PackLevel Level => PackLevel.Application;

        /// <summary>
        /// 获取 模块启动顺序编号
        /// <para>模块启动的顺序先按级别启动，级别内部再按此顺序启动，级别默认为0，表示无依赖，需要在同级别有依赖顺序的时候，再重写为 >0 的顺序值。</para>
        /// </summary>
        public override int OrderNo => 99;
        #endregion

        #endregion

        #region "方法"
        #region "应用AspNetCore的服务业务"
        /// <summary>
        /// 应用AspNetCore的服务业务
        /// </summary>
        /// <param name="app">Web应用程序</param>
        public override void UsePack(WebApplication app)
        {
            MapMvc(app);
            MapSignalR(app);
            MapOther(app);

            IsEnabled = true;
        }
        #endregion
        #region "重写以配置MVC的路由"
        /// <summary>
        /// 重写以配置MVC的路由
        /// </summary>
        /// <param name="app">Web应用程序</param>
        /// <returns></returns>
        protected virtual WebApplication MapMvc(WebApplication app)
        {
            app.MapControllersWithAreaRoute();

            return app;
        }
        #endregion
        #region "重写以配置SignalR的路由"
        /// <summary>
        /// 重写以配置SignalR的终结点
        /// ，在这实现Hub的路由映射，例如：endpoints.MapHub{ChatHub}(routePattern);
        /// </summary>
        /// <param name="app">Web应用程序</param>
        /// <returns></returns>
        protected virtual WebApplication MapSignalR(WebApplication app)
        {
            // 在这实现Hub的路由映射
            // 例如：app.MapHub<ChatHub>();

            var provider = app.Services;

            var options = provider.GetMicroCloudOptions();

            if (options?.SignalR?.Enabled != true)
            {
                return app;
            }

            string routePattern = options.SignalR.RoutePattern;
            if (routePattern.IsMissing())
            {
                throw new Exception(I18N.T("配置文件中 SignalR 节点的 RoutePattern 不能为空"));
            }
            if (!routePattern.StartsWith("/"))
            {
                throw new Exception(I18N.T("配置文件中 SignalR 节点的 RoutePattern 值必须以 '/' 开头"));
            }

            app.MapHub<SignalRHub>(routePattern);

            return app;
        }
        #endregion
        #region "重写以配置其他路由"
        /// <summary>
        /// 重写以配置其他终结点
        /// </summary>
        /// <param name="app">Web应用程序</param>
        /// <returns></returns>
        protected virtual WebApplication MapOther(WebApplication app)
        {
            return app;
        }
        #endregion

        #endregion

    }

}
